from contextlib import asynccontextmanager

from fastapi import FastAPI, Depends
from starlette.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles

from config.exceptions import register_exception_handlers
from controllers.auth import token, get_current_active_user
from controllers.permission_controller import permissions
from controllers.role_controller import roles
from controllers.upload import upload
from controllers.user_controller import users
from db.mysql_db import create_db_and_tables, mysql_db


@asynccontextmanager
async def lifespan(app: FastAPI):
    create_db_and_tables()
    yield
    mysql_db.engine.dispose()



app = FastAPI(lifespan=lifespan)

register_exception_handlers(app)

app.mount("/static", StaticFiles(directory="static"), name="static")

app.add_middleware(
       CORSMiddleware,
       allow_origins=["*"],  # 允许所有来源
       allow_credentials=True,  # 允许凭据（例如 cookies）
       allow_methods=["*"],  # 允许所有 HTTP 方法
       allow_headers=["*"],  # 允许所有头部
   )

app.include_router(users, dependencies=[Depends(get_current_active_user)])
app.include_router(roles, dependencies=[Depends(get_current_active_user)])

app.include_router(permissions, dependencies=[Depends(get_current_active_user)])

app.include_router(upload, dependencies=[Depends(get_current_active_user)])

app.include_router(token)
